package com.sbxBase.service.impl;

import com.sbxBase.entity.FriendsApply;
import com.sbxBase.mapper.FriendsApplyMapper;
import com.sbxBase.service.FriendsApplyService;
import com.sbxBase.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.entity.sbxBase.User;
import com.common.utils.RequestUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Service
public class FriendsApplyServiceImpl implements FriendsApplyService {

    @Resource
    private FriendsApplyMapper friendsApplyMapper;
    @Resource
    private UserService userService;

    @Override
    public void apply(String action, String id,String result) {
        FriendsApply friendsApply = friendsApplyMapper.selectById(id);
        if (Objects.isNull(friendsApply)) {
            throw new IllegalArgumentException("不存在申请");
        }
        if ("affirm".equalsIgnoreCase(action)) {
            friendsApply.setStatus("agree");
        } else if ("refuse".equalsIgnoreCase(action)) {
            friendsApply.setStatus("refuse");
        } else {
            throw new IllegalArgumentException("不存在的操作" + action);
        }
        friendsApply.setUpdated(new Date());
        friendsApply.setHandleResult(result);
        friendsApplyMapper.updateById(friendsApply);

    }

    @Override
    public Page<FriendsApply> getApplyPage(Integer pageIndex, Integer pageSize) {
        Page<FriendsApply> friendsApplyPage = new Page<>(pageIndex, pageSize);

        friendsApplyPage = friendsApplyMapper.selectPage(friendsApplyPage, new LambdaQueryWrapper<>());

        return friendsApplyPage;

    }

    @Override
    public void submitApply(String userId, String cause) {
        User userById = userService.getUserById(userId);
        if (Objects.isNull(userById)) {
            throw new IllegalArgumentException("用户不存在");
        }
        FriendsApply friendsApply = new FriendsApply();
        friendsApply.setApplyCause(cause);
        friendsApply.setHandleId(userId);
        friendsApply.setCreated(new Date());
        friendsApply.setStatus("init");
        friendsApply.setApplicantId(RequestUtil.getLoginUserId());
        friendsApplyMapper.insert(friendsApply);
    }
}
